<template>
  <div class="app-container">
    <el-page-header
      content="性能测试 - 报告详情"
      style="margin-bottom: 20px"
      @back="goBack"
    />
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header><strong> 报告信息 </strong></template>
          <el-form
            label-position="left"
            label-width="100px"
            style="margin-left: 20px; word-break: break-all; width: 100%; height: 300px"
            :model="resultData"
          >
            <el-form-item label="结果id：" style="margin: 10px 0;">
              <span>{{ resultData.id }}</span>
            </el-form-item>
            <el-form-item label="测试套件：" style="margin: 10px 0;">
              <span>「{{ resultData.suiteId }}」{{ resultData.suiteName }}</span>
            </el-form-item>
            <el-form-item label="执行用户：" style="margin: 10px 0;">
              <span>{{ resultData.runUser }}</span>
            </el-form-item>
            <el-form-item label="运行状态：" style="margin: 10px 0;">
              <el-tag style="margin-left: 0px" size="small" :type="getRunStatusName(resultData.status)==='通过'?'success':getRunStatusName(resultData.status)==='警告'?'warning':getRunStatusName(resultData.status) === '失败'? 'danger' : 'info'">
                <i v-if="getRunStatusName(resultData.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
                {{ getRunStatusName(resultData.status) }}
              </el-tag>
              <el-checkbox v-if="getRunStatusName(resultData.status) !== '通过'" v-model="onlyShowFailed" style="margin-left: 10px;">只显示未通过的结果</el-checkbox>
            </el-form-item>
            <el-form-item label="创建时间：" style="margin: 10px 0;">
              <span>{{ resultData.createdAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="结束时间：" style="margin: 10px 0;">
              <span>{{ resultData.endAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="总耗时：" style="margin: 10px 0;">
              <span>{{ resultData.totalTime }}</span>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div ref="chart" style="width: 100%;height: 365px;" />
        </el-card>
      </el-col>
    </el-row>
    <el-divider><span style="color: #909399;"> 运行信息 </span></el-divider>
    <el-card shadow="hover">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item
          v-for="item in resultData.perfTestResultTestScriptList"
          v-show="!onlyShowFailed || item.status !== 4"
          :key="item.id"
          style="position: relative"
          @click.native="handleClick(item.testScriptId, item.status)"
        >
          <template #title>
            测试脚本：
            <strong style="color: #606266">
              「
              <a
                :href="`/#/performance_test/test_script?id=${item.testScriptId}`"
                target="_blank"
                style="color: #409eff"
              >
                {{ item.testScriptId }}
              </a>
              」
              {{ item.testScriptName }}
            </strong>
            <el-tag style="margin-left: 15px" size="small" :type="getRunStatusElTagType(item.status)">
              <i v-if="getRunStatusName(item.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
              {{ getRunStatusName(item.status) }}
            </el-tag>
          </template>
          <el-alert close-text="Get!" show-icon style="margin-bottom: 10px" type="info">
            <span v-if="item.status === getRunStatusValue('待运行')">
              <div>1、待运行状态的测试脚本，主要查看 日志 即可</div>
              <div>2、由于环境检查时间较长，所以在没有正常运行压测脚本前都是待运行状态</div>
              <div>3、日志 中展示了所有的信息，包括 环境检查执行的命令、启动脚本执行的命令、采集回来的性能测试结果 等</div>
              <div>4、由于测试脚本运行状态不是实时刷新的，通过页面刷新可以更新测试脚本运行状态</div>
            </span>
            <span v-if="item.status === getRunStatusValue('运行中')">
              <div>1、运行中状态的测试脚本，主要查看 实时图表 即可</div>
              <div>2、实时图表 中主要显示 测试接口、响应时间、QPS 等数据。响应时间图表、QPS图表 等图表</div>
            </span>
            <span v-if="item.status === getRunStatusValue('通过')">
              <div>1、通过状态的测试脚本，主要查看 测试报告 即可</div>
              <div>2、测试报告 中主要显示 测试接口、响应时间、QPS 等数据</div>
            </span>
            <span v-if="item.status === getRunStatusValue('错误')">
              <div>1、错误状态的测试脚本，主要查看 日志 即可</div>
              <div>2、错误状态一般表示 agent 未能正常运行压测脚本。出现这种情况可能是 python 脚本有致命 bug，也可能是 agent 存在 bug</div>
              <div>3、一般在 日志 最后可以找到对应的报错</div>
            </span>
            <span v-if="item.status === getRunStatusValue('中断')">
              <div>1、当手动中断套件的运行时，测试脚本的是 中断状态</div>
              <div>2、中断状态的测试脚本，可能需要查看 测试报告、实时图表 或 日志，这取决于中断当时执行到的位置</div>
            </span>
            <span v-if="item.status === getRunStatusValue('失败')">
              <div>1、失败状态的测试脚本，主要查看 测试报告 即可</div>
              <div>2、失败状态一般表示 agent 能正常运行压测脚本。出现这种情况可能是 响应时间 或 资源消耗 大比例差于基线数据</div>
              <div>3、在 测试报告 中可以查看是那里出现了问题</div>
            </span>
          </el-alert>
          <el-card shadow="box-card">
            <el-tabs v-model="resultActiveName" @tab-click="handleTabClick">
              <el-tab-pane label="测试报告" name="report" />
              <el-tab-pane label="实时图表" name="chart" />
              <!-- <el-tab-pane label="数据下载" name="download" />-->
              <el-tab-pane label="日志" name="log" />
            </el-tabs>

            <!-- 测试报告 -->
            <div v-if="resultActiveName === 'report'">
              <!-- 测试报告 - 与基线比对 -->
              <div v-if="(report.diffResult.csvRequests && report.diffResult.csvRequests.length >0) || (report.diffResult.csvExceptions && report.diffResult.csvExceptions.length >0) || (report.diffResult.csvFailures && report.diffResult.csvFailures.length >0)" style="margin-bottom: 40px;">
                <div>
                  <span>与基线比对</span>
                </div>
                <el-descriptions class="margin-top" :column="1" :size="size" border :label-style="{ 'font-weight': 'bold', 'color': '#909399', 'width': '120px' }">
                  <el-descriptions-item v-if="report.diffResult.csvRequests && report.diffResult.csvRequests.length >0">
                    <template slot="label">csvRequests</template>
                    <ol>
                      <li v-for="item in report.diffResult.csvRequests" :key="item">{{ item }}</li>
                    </ol>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="report.diffResult.csvFailures && report.diffResult.csvFailures.length >0">
                    <template slot="label">csvFailures</template>
                    <ol>
                      <li v-for="item in report.diffResult.csvFailures" :key="item">{{ item }}</li>
                    </ol>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="report.diffResult.csvExceptions && report.diffResult.csvExceptions.length >0">
                    <template slot="label">csvExceptions</template>
                    <ol>
                      <li v-for="item in report.diffResult.csvExceptions" :key="item">{{ item }}</li>
                    </ol>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <!-- 测试报告 - 请求 统计信息（Request Statistics） -->
              <div>
                <span>请求 统计信息（Request Statistics）</span>
              </div>
              <el-table :data="report.requests.body" border style="width: 100%">
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>请求类型</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求类型。例如：POST、GET 等">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.type }}</template>
                </el-table-column>
                <el-table-column>
                  <template slot="header">
                    <span>请求路径</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求路径（地址）">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">
                    <span v-if="row.name === 'Aggregated'">汇总</span>
                    <span v-else>{{ row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>请求总数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="已完成的请求总数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.requestCount }}</template>
                </el-table-column>
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>失败总数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="失败的请求总数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.failureCount }}</template>
                </el-table-column>
                <el-table-column label="响应时间（毫秒）" align="center">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>平均</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="平均响应时间（Average Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.averageResponseTime) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>中位</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="响应时间的中位数（Median Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.medianResponseTime) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>最小</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="最小响应时间（Min Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.minResponseTime) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>最大</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="最大响应时间（Max Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.maxResponseTime) }}</template>
                  </el-table-column>
                </el-table-column>
                <el-table-column align="center" width="110px">
                  <template slot="header">
                    <span>每秒请求数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="每秒处理的请求个数（RPS / QPS）">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.requestsPerSec * 100) / 100 }}</template>
                </el-table-column>
                <el-table-column align="center" width="110px">
                  <template slot="header">
                    <span>每秒失败数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="每秒失败的请求个数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.failuresPerSec * 100) / 100 }}</template>
                </el-table-column>
                <el-table-column align="center" width="150px">
                  <template slot="header">
                    <span>平均大小（字节）</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="单个请求的平均大小">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.averageContentSize) }}</template>
                </el-table-column>
              </el-table>
              <!-- 测试报告 - 响应时间 统计信息（Response Time Statistics） -->
              <div style="margin-top: 40px;">
                <span>响应时间 统计信息（Response Time Statistics）</span>
              </div>
              <el-table :data="report.requests.body" border style="width: 100%">
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>请求类型</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求类型。例如：POST、GET 等">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.type }}</template>
                </el-table-column>
                <el-table-column>
                  <template slot="header">
                    <span>请求路径</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求路径（地址）">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">
                    <span v-if="row.name === 'Aggregated'">汇总</span>
                    <span v-else>{{ row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="响应时间（毫秒）" align="center">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>50%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="50% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent50) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>66%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="66% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent66) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>75%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="75% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent75) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>80%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="80% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent80) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>90%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="90% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent90) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>95%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="95% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent95) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>98%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="98% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent98) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>99%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="99% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent99) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>99.9%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="99.9% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent99Point9) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>99.99%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="99.99% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent99Point99) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>100%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="100% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.percent100) }}</template>
                  </el-table-column>
                </el-table-column>
              </el-table>
              <!-- 测试报告 - 异常 统计信息（Exceptions Statistics） -->
              <div v-if="report.exceptions.body && report.exceptions.body.length >0" style="margin-top: 40px;">
                <span>异常 统计信息（Exceptions Statistics）</span>
                <el-table :data="report.exceptions.body" border style="width: 100%" :header-cell-style="{ background: '#F5F7FA', color: '#909399' }">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>次数</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="此异常出现的总次数（Count）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.count }}</template>
                  </el-table-column>
                  <el-table-column min-width="40%">
                    <template slot="header">
                      <span>异常信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="脚本语法错误引发的异常（Message）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.message }}</template>
                  </el-table-column>
                  <el-table-column min-width="60%">
                    <template slot="header">
                      <span>异常详细信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="包括 异常的文件路径和行号 和 异常调用堆栈信息 等（Traceback）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.traceback }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="150px">
                    <template slot="header">
                      <span>节点</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="那个节点出现的异常（Nodes）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.nodes }}</template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 测试报告 - 失败 统计信息（Failures Statistics） -->
              <div v-if="report.failures.body && report.failures.body.length >0" style="margin-top: 40px;">
                <span>失败 统计信息（Failures Statistics）</span>
                <el-table :data="report.failures.body" border style="width: 100%" :header-cell-style="{ background: '#F5F7FA', color: '#909399' }">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>请求类型</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求类型。例如：POST、GET 等">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.method }}</template>
                  </el-table-column>
                  <el-table-column min-width="40%">
                    <template slot="header">
                      <span>请求路径</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求路径（地址）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">
                      <span v-if="row.name === 'Aggregated'">汇总</span>
                      <span v-else>{{ row.name }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="60%">
                    <template slot="header">
                      <span>错误信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="脚本抛出的业务错误（Error）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.error }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>次数</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="此错误出现的总次数（Occurrences）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.occurrences }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 实时图表 -->
            <div v-if="resultActiveName === 'chart'">
              <!-- 实时图表 - 请求（Request） -->
              <div>
                <span>请求（Request）</span>
              </div>
              <el-table :data="latestData.requests.stats" border style="width: 100%">
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>请求类型</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求类型。例如：POST、GET 等">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.method }}</template>
                </el-table-column>
                <el-table-column>
                  <template slot="header">
                    <span>请求路径</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求路径（地址）">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">
                    <span v-if="row.name === 'Aggregated'">汇总</span>
                    <span v-else>{{ row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>请求总数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="已完成的请求总数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.num_requests }}</template>
                </el-table-column>
                <el-table-column align="center" width="100px">
                  <template slot="header">
                    <span>失败总数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="失败的请求总数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ row.num_failures }}</template>
                </el-table-column>
                <el-table-column label="响应时间（毫秒）" align="center">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>中位</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="响应时间的中位数（Median Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.median_response_time) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>90%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="90% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.ninetieth_response_time) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>99%</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="99% 的请求在这个时间内得到响应">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.ninety_ninth_response_time) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>平均</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="平均响应时间（Average Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.avg_response_time) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>最小</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="最小响应时间（Min Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.min_response_time) }}</template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>最大</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="最大响应时间（Max Response Time）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ Math.floor(row.max_response_time) }}</template>
                  </el-table-column>
                </el-table-column>
                <el-table-column align="center" width="150px">
                  <template slot="header">
                    <span>平均大小（字节）</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="单个请求的平均大小">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.avg_content_length) }}</template>
                </el-table-column>
                <el-table-column align="center" width="110px">
                  <template slot="header">
                    <span>每秒请求数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="每秒处理的请求个数（RPS / QPS）">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.current_rps * 100) / 100 }}</template>
                </el-table-column>
                <el-table-column align="center" width="110px">
                  <template slot="header">
                    <span>每秒失败数</span>
                    <el-tooltip class="item" effect="dark" placement="top" content="每秒失败的请求个数">
                      <i class="el-icon-question" style="margin-left: 3px;" />
                    </el-tooltip>
                  </template>
                  <template v-slot="{row}">{{ Math.floor(row.current_fail_per_sec * 100) / 100 }}</template>
                </el-table-column>
              </el-table>
              <!-- 实时图表 - 失败（Failures） -->
              <div v-if="latestData.requests.errors && latestData.requests.errors.length >0" style="margin-top: 40px;">
                <span>失败（Failures）</span>
                <el-table :data="latestData.requests.errors" border style="width: 100%" :header-cell-style="{ background: '#F5F7FA', color: '#909399' }">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>请求类型</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求类型。例如：POST、GET 等">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.method }}</template>
                  </el-table-column>
                  <el-table-column min-width="40%">
                    <template slot="header">
                      <span>请求路径</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="HTTP 请求路径（地址）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">
                      <span v-if="row.name === 'Aggregated'">汇总</span>
                      <span v-else>{{ row.name }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="60%">
                    <template slot="header">
                      <span>错误信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="脚本抛出的业务错误（Error）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}"><span v-html="row.error" /></template>
                  </el-table-column>
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>次数</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="此错误出现的总次数（Occurrences）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.occurrences }}</template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 实时图表 - 异常（Exceptions） -->
              <div v-if="latestData.exceptions.exceptions && latestData.exceptions.exceptions.length >0" style="margin-top: 40px;">
                <span>异常（Exceptions）</span>
                <el-table :data="latestData.exceptions.exceptions" border style="width: 100%" :header-cell-style="{ background: '#F5F7FA', color: '#909399' }">
                  <el-table-column align="center" width="100px">
                    <template slot="header">
                      <span>次数</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="此异常出现的总次数（Count）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.count }}</template>
                  </el-table-column>
                  <el-table-column min-width="40%">
                    <template slot="header">
                      <span>异常信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="脚本语法错误引发的异常（Message）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.msg }}</template>
                  </el-table-column>
                  <el-table-column min-width="60%">
                    <template slot="header">
                      <span>异常详细信息</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="包括 异常的文件路径和行号 和 异常调用堆栈信息 等（Traceback）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}"><span v-html="$options.filters.translateHtml($options.filters.textareaFormat($options.filters.html2Escape(row.traceback)))" /></template>
                  </el-table-column>
                  <el-table-column align="center" width="150px">
                    <template slot="header">
                      <span>节点</span>
                      <el-tooltip class="item" effect="dark" placement="top" content="那个节点出现的异常（Nodes）">
                        <i class="el-icon-question" style="margin-left: 3px;" />
                      </el-tooltip>
                    </template>
                    <template v-slot="{row}">{{ row.nodes }}</template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 实时图表 - 每秒请求 -->
              <div style="margin-top: 40px;">
                <span style="margin-left: 10px; color: rgba(0, 0, 0, 0.45);"><b>每秒请求</b></span>
                <div style="border:solid 1px #dfe4ed; margin-top: -27px;" class="json-editor">
                  <LineChart :filter-all-zero-data="false" :categories="timeList" :data="requestsPerSecList" height="350px" />
                </div>
              </div>
              <!-- 实时图表 - 响应时间（ms） -->
              <div style="margin-top: 40px;">
                <span style="margin-left: 10px; color: rgba(0, 0, 0, 0.45);"><b>响应时间（ms）</b></span>
                <div style="border:solid 1px #dfe4ed; margin-top: -27px;" class="json-editor">
                  <LineChart :filter-all-zero-data="false" :categories="timeList" :data="responseTimeList" height="350px" />
                </div>
              </div>
              <!-- 实时图表 - 用户数量 -->
              <div style="margin-top: 40px;">
                <span style="margin-left: 10px; color: rgba(0, 0, 0, 0.45);"><b>用户数量</b></span>
                <div style="border:solid 1px #dfe4ed; margin-top: -27px;" class="json-editor">
                  <LineChart :filter-all-zero-data="false" :categories="timeList" :data="userCountList" height="350px" />
                </div>
              </div>
            </div>

            <!-- 日志 -->
            <div v-if="resultActiveName === 'log'">
              <el-table :data="stepDetail" border style="width: 100%">
                <el-table-column align="center" label="状态" width="70px">
                  <template v-slot="scope">
                    <i v-if="scope.row.status <= 3" class="el-icon-success" style="color: #67c23a" />
                    <i v-if="scope.row.status === 4" class="el-icon-info" style="color: #409eff" />
                    <i v-if="scope.row.status >= 5 && scope.row.status <= 11" class="el-icon-warning" style="color: #e6a23c" />
                    <i v-if="scope.row.status >= 12" class="el-icon-error" style="color: #f56c6c" />
                  </template>
                </el-table-column>
                <el-table-column label="Agent" width="180px">
                  <template>{{ item.agentName }}</template>
                </el-table-column>
                <el-table-column label="详情">
                  <template v-slot="scope">
                    <el-tag v-show="scope.row.desc" style="margin-right: 5px;">{{ scope.row.desc }}</el-tag>
                    <el-tag v-show="scope.row.type" style="margin-right: 5px;">{{ scope.row.type }}</el-tag>
                    <span v-html="$options.filters.translateHtml($options.filters.textareaFormat($options.filters.html2Escape(scope.row.log)))" />
                  </template>
                </el-table-column>
                <el-table-column label="运行时间" width="80">
                  <template v-slot="scope">
                    <span>{{ scope.row.createdAt | parseTime('{h}:{i}:{s}') }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getPerfTestResultInfoById, getCaseResultDetails, perfTestResultGetReport, perfTestResultGetLatestData, perfTestResultGetChart } from '@/api/performance_test/perf_test_result'
import { getRunStatusValue, getRunStatusName, getRunStatusElTagType, getRunStatusColor } from '@/enum/runStatus.js'
import LineChart from '@/components/Charts/LineChart'
import { updateCurrentCompanyProject } from '@/api/user'

export default {
  components: { LineChart },
  filters: {
    // 转义html标签，会将 & 转为 &amp; < 转为 &lt; > 转为 &gt;
    html2Escape(text) {
      return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    },
    // 将 \n 和 \r\n 转为 <br/>
    textareaFormat: function(text) {
      return text.replace(/\n|\r\n/g, '<br/>')
    },
    // 将 http 或 https 转为 <a> 标签
    translateHtml: function(msg) {
      return msg.replace(
        /((http|https|ftp|file):\/\/[-A-Za-z0-9+&@#()/%?=~_|!:,.\\;]+[-A-Za-z0-9+&@#()/%=~_\\|])/g,
        `<a style='color:#2660f5;text-decoration:underline;cursor:hand;' href="$1" target="_blank">$1</a>`
      )
    }
  },
  data() {
    var option = {
      title: {
        text: '用例运行状态分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'right'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: this.echartsData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(10, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    return {
      resultActiveName: 'report',
      activeName: '0',
      stepActiveName: '',
      chart: null,
      myChart: null,
      option,
      resultId: this.$route.query.resultId,
      testScriptId: undefined,
      type: this.$route.query.type,
      resultData: {},
      stepDetail: [],
      echartsData: [],
      dataMap: [],
      caseList: [],
      report: {
        diffResult: {},
        requests: {},
        failures: {},
        exceptions: {}
      },
      latestData: {
        requests: {},
        exceptions: {},
        tasks: {}
      },
      timeList: [],
      requestsPerSecList: [],
      responseTimeList: [],
      userCountList: [],
      isOpen: false,
      onlyShowFailed: false
    }
  },
  watch: {
    echartsData(newVal) {
      this.chart.setOption({
        series: [{
          data: newVal
        }]
      })
    },
    activeName(newVal) {
      if (newVal) {
        this.isOpen = true
      } else {
        this.isOpen = false
      }
    }
  },
  mounted() {
    this.initChart()
    this.get_result_info()

    // 如果 url 中的 projectId 跟 store 中的 projectId 不同，则切换到 url 中的项目
    if (this.$route.query.companyId && this.$route.query.projectId && (Number(this.$route.query.companyId) !== this.$store.getters.companyId || Number(this.$route.query.projectId) !== this.$store.getters.projectId)) {
      const tmp = {
        companyId: this.$route.query.companyId,
        projectId: this.$route.query.projectId
      }
      updateCurrentCompanyProject(tmp).then(response => {
        // 调用后台接口，更新用户当前 产品-项目 成功后，修改 前端store 中的 companyId、projectId
        this.$store.dispatch('user/updateCompanyIdProjectId', tmp).then(() => {
        })
      })
    }
  },
  created() {
  },
  beforeDestroy() {
    this.chart.dispose()
  },
  methods: {
    getRunStatusValue,
    getRunStatusName,
    getRunStatusElTagType,
    /**
     * 点击 el-card 上的一行（测试脚本）
     * @param testScriptId 测试脚本 id
     * @param testScriptStatus 测试脚本 运行状态
     */
    handleClick(testScriptId, testScriptStatus) {
      if (this.isOpen) {
        if (testScriptStatus === getRunStatusValue('待运行') || testScriptStatus === getRunStatusValue('错误') || testScriptStatus === getRunStatusValue('中断')) {
          this.resultActiveName = 'log'
        } else if (testScriptStatus === getRunStatusValue('通过') || testScriptStatus === getRunStatusValue('失败')) {
          this.resultActiveName = 'report'
        } else if (testScriptStatus === getRunStatusValue('运行中')) {
          this.resultActiveName = 'chart'
        }
        this.testScriptId = testScriptId
        this.handleTabClick()
        this.isOpen = false
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.option)
    },
    get_result_info: function() {
      getPerfTestResultInfoById(this.$store.getters.projectId, this.resultId).then(response => {
        this.resultData = response.data
        this.caseList = response.data.perfTestResultTestScriptList
        this.caseList.forEach(item => {
          this.dataMap.push(item.status)
        })
        var arrTmp = []
        this.dataMap.forEach((val) => {
          if (arrTmp.indexOf(val) === -1) {
            this.echartsData.push({
              name: this.getRunStatusName(val),
              value: this.dataMap.filter(v => v === val).length,
              itemStyle: { 'color': getRunStatusColor(val) }
            })
            arrTmp.push(val)
          }
        })
      })
    },
    goBack() {
      this.$router.back()
    },
    // tab 切换
    handleTabClick() {
      if (this.resultActiveName === 'report') {
        perfTestResultGetReport(this.resultId, this.testScriptId).then(response => {
          this.report = response.data
        })
      } else if (this.resultActiveName === 'chart') {
        perfTestResultGetLatestData(this.resultId, this.testScriptId).then(response => {
          this.latestData = response.data
        })
        perfTestResultGetChart(this.resultId, this.testScriptId).then(response => {
          this.timeList = response.data.time
          this.requestsPerSecList = [
            { 'data': response.data.currentRequestsPerSec, 'name': '每秒请求（RPS / QPS）' },
            { 'data': response.data.currentFailPerSec, 'name': '每秒失败' }
          ]
          this.responseTimeList = [
            { 'data': response.data.responseTimePercentile50, 'name': '50% 响应时间' },
            { 'data': response.data.responseTimePercentile95, 'name': '95% 响应时间' }
          ]
          this.userCountList = [
            { 'data': response.data.userCount, 'name': '用户' }
          ]
        })
      } else if (this.resultActiveName === 'log') {
        getCaseResultDetails(this.resultId, this.testScriptId).then(response => {
          this.stepDetail = response.data
        })
      }
    }
  }
}
</script>
